package com.lh.io.bio;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

/**
 * 客户端每发起一个请求，服务端就创建一个新的线程来处理这个客户端的请求，
 * 这样就实现了一个客户端一个线程的模型
 */

public class ThreadServer {


    public static void main(String[] args) {

        try {
            ServerSocket socket = new ServerSocket(8088);

            ExecutorService executorService = new ExecutorService();
            Executor executor = executorService.getExecutor();

            while (true) {
                Socket accept = socket.accept();

                executor.execute(() -> {
                    try {
                        InputStream is = accept.getInputStream();
                        BufferedReader br = new BufferedReader(new InputStreamReader(is));

                        String msg;
                        while ((msg = br.readLine()) != null) {
                            System.out.println(msg);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
